﻿using System;
using System.Collections.Generic;
using System.Text;
using Authorize.Application.ClientSource.Model;
using Authorize.Core.Cache;
using Authorize.Core.Entity;
using Authorize.Core.Repository;
using Authorize.Core.Repository.Implement;
using AutoMapper;

namespace Authorize.Application.ClientSource
{
    public class ClientSourceService : IClientSourceService
    {
        private readonly IClientSourceRepository _repository;

        public ClientSourceService()
        {
            _repository = new ClientSourceRepository();
        }

        public List<ClientSourceModel> GetList()
        {
            var entities = _repository.GetAll();
            return Mapper.Map<List<ClientSourceModel>>(entities);
        }

        public ClientSourceModel Create(ClientSourceInputModel model)
        {
            var entity = Mapper.Map<ClientSourceEntity>(model);
            entity.Id = Guid.NewGuid();
            entity.CreateDate = DateTime.Now;
            entity.UpdateDate = DateTime.Now;
            _repository.Add(entity);
            ConstDataCache.AddClient(entity);
            return Mapper.Map<ClientSourceModel>(entity);
        }

        public ClientSourceModel Get(Guid id)
        {
            return Mapper.Map<ClientSourceModel>(_repository.GetFirst(x => x.Id == id));
        }

        public bool Modify(ClientSourceModel model)
        {
            var entity = _repository.GetFirst(x => x.Id == model.Id);
            entity.UpdateDate = DateTime.Now;
            Mapper.Map(model, entity);
            _repository.Modify(entity);
            ConstDataCache.AddClient(entity);
            return true;
        }

        public bool Delete(Guid id)
        {
            var entity = _repository.Get(id);
            ConstDataCache.RemoveClient(entity.ClientId);
            return _repository.Delete(id);
        }
    }
}
